import json

import matplotlib.pyplot as plt

import Template as tp
import MatchDigit as md
import myfuncs as mf
import cv2
import MatchConsumeType as mct
from DataIntegrator import DataIntegrator

if __name__ == '__main__':
    # 指定操作对象
    operandPath = 'operands/operand4.jpg'
    # 初始化数据整合模块
    dataIntegrator = DataIntegrator()
    # 初始化并取得数字模版
    numberTemplate = tp.Template("templates/DIGIT_25x36_Templates.jpg", singleTemplateSize=(36, 25), outputSize=(13, 9))  # singleTemplate的原始大小是27*36
    numberTemplates = numberTemplate.getTemplates()
    # for i, t in enumerate(numberTemplates.items()):
    #     plt.subplot(3, 5, i + 1)
    #     plt.imshow(t[1])
    # plt.show()

    # 初始化数字匹配模块并使用模版进行匹配
    numberOperand = md.MatchDigit(operandPath, width=360, singleTemplateSize=(9, 13))
    numberOperand.matchDigit(numberTemplates)
    # 绑定数字数据到整合模块
    dataIntegrator.bindData(numberOperand.getMatchResults(), 'accountValue')
    resultImage = numberOperand.drawResults()
    mf.showImage('result', resultImage)
    # 获取已识别的区域，在以后的操作中忽略这些区域减少运算
    hit, miss = numberOperand.getOperatedArea()
    # 初始化消费类型匹配模块
    accountTypeOperand = mct.MatchConsumeType(operandPath, width=540)
    accountTypeOperand.bindTemplateIndexes('DATETIME_64x64_Templates', './templates/DATETIME_64x64_Templates.json')
    # 计算除去miss的ROI
    accountTypeOperand.calcROI(miss)
    # rectLocations中包含{
    #   'datetimeROI', 'datPosition', 'accountROI', 'accPosition'
    # }
    rectLocations = accountTypeOperand.findRectROI(accountTypeOperand.imageROI)
    # 分别计算匹配结果
    datetimeTemplate = tp.Template("templates/DATETIME_64x64_Templates.jpg", (64, 64), (64, 64))
    datetimeTemplates = datetimeTemplate.getTemplates()
    # mf.showImages(datetimeTemplates)
    accountDatetimeResults = accountTypeOperand.matchDatetime(rectLocations, datetimeTemplates)
    accountTypeResults = accountTypeOperand.matchAccountType(rectLocations)
    # 绑定匹配结果到整合模块
    dataIntegrator.bindData(accountTypeResults, 'accountType')
    dataIntegrator.bindData(accountDatetimeResults, 'accountDatetime')
    print(dataIntegrator.getData())
    jText = json.dumps(dataIntegrator.getData(), indent=2, ensure_ascii=False)
    with open('output.json', 'w', encoding='utf-8') as f:
        f.write(jText)
    f.close()
